var prefix = jsctx + "/tenantOperator";

var tenantOperator = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/list",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20],
                    pageNumber: 1,
                    sidePagination: "server",
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            operatorName: $('#operatorName').val(),
                            tenantOperatorCode: $('#tenantOperatorCode').val(),
                            loginName: $('#loginName').val()
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },


                        {field: 'tenantOperatorCode', title: '分销商编号'},
                        {field: 'operatorName', title: '分销商名称'},
                        {field: 'loginName', title: '登录帐号'},
                        {field: 'phone', title: '手机号'},
                        {field: 'contactName', title: '联系人'},
                        {field: 'address', title: '公司地址'},
                        {
                            field: 'status',
                            title: '状态'
                        },
                        {field: 'createdTime', title: '创建时间'},
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '300', align: 'center',
                            formatter: function (value, row, index) {
                                var a = '';
                                var b = '';
                                var c = '';
                                var d = '';
                                if (Tenant_tenantOperatorUser_update) {
                                    a = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="编辑" onclick="tenantOperator.edit(\''
                                        + row.tenantOperatorCode
                                        + '\')">编辑</a> ';
                                    b = '<a class="btn btn-success btn-sm" href="#" title="设置密码" onclick="tenantOperator.updateOperatorPassword(\''
                                        + row.loginName
                                        + '\')">设置密码</a> ';
                                    if (row.status == "0") {
                                        c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="更改状态" onclick="tenantOperator.updateStatus(\''
                                            + row.loginName
                                            + '\')">冻结</a>';
                                    } else if (row.status == "1") {
                                        c = '<a class="btn btn-info btn-sm ' + has_edit + '" href="#" title="更改状态" onclick="tenantOperator.updateStatus(\''
                                            + row.loginName
                                            + '\')">恢复</a>';
                                    }
                                }
                                if (Tenant_tenantOperatorUser_look){
                                    d = '<a class="btn btn-info btn-sm" href="#" title="查看桩群" onclick="tenantOperator.operatorElecStation(\''
                                        + row.tenantOperatorCode
                                        + '\')">查看桩群</a> ';
                                }
                                return a + b + c + d;
                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function add() {
        location.href = prefix + "/add";
    }


    function updateOperatorPassword(loginName) {
//  $("#recipient-name").val(sort)
        //  $("#ulId").val(ulId)
        $('#exampleModal').modal('show')

        $("#updateOperatorPassword").unbind("click").bind("click", function () {

            var formData = new FormData();
            formData.append("password", $("#password").val());
            formData.append("verifyPassword", $("#verifyPassword").val());
            formData.append("loginName", loginName);
            $.ajax({
                url: prefix + "/updateOperatorPassword",
                type: "post",
                data: formData,
                dataType: "json",
                processData: false, // 告诉jQuery不要去处理发送的数据，用于对data参数进行序列化处理 这里必须false
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        //  $('#exampleModal').modal('hide')
                    }

                }
            })
        })

    }


    // function remove(id, name) {
    //     layer.confirm('确定要删除选中的记录？' + name, {
    //         btn: ['确定', '取消']
    //     }, function (index) {
    //         $.ajax({
    //             url: prefix + "/remove",
    //             type: "post",
    //             data: {
    //                 'id': id
    //             },
    //             success: function (data) {
    //                 layer.close(index);
    //                 if (data.status == 200) {
    //                     layer.msg("删除成功");
    //                     reLoad();
    //                 } else {
    //                     layer.msg(data.message);
    //                 }
    //             }
    //         });
    //     })
    // }

    function edit(id) {
        location.href = prefix + "/edit/" + id;
    }

    function resetPwd(loginName, name) {
        layer.confirm('重置后的新密码将发到你绑定的手机，确定要重置密码？' + name, {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/resetPwd",
                type: "post",
                data: {
                    'loginName': loginName
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("成功重置密码");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function goBack() {
        location.href = prefix + "/index";
    }

    /**
     * 修改状态
     * @param loginName
     */
    function updateStatus(loginName) {
        layer.confirm('确定要修改状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'loginName': loginName
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function operatorElecStation(tenantOperatorCode) {
        location.href = prefix + "/operatorElecStation/" + tenantOperatorCode;
    }

    function exportTenantOperator() {
        $.fileDownload(prefix + "/exportTenantOperator", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                loginName: $("#loginName").val().trim(),
                tenantOperatorCode: $("#tenantOperatorCode").val().trim(),
                operatorName: $("#operatorName").val().trim(),
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })

    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        add: add,
        edit: edit,
        resetPwd: resetPwd,
        updateStatus: updateStatus,
        operatorElecStation: operatorElecStation,
        updateOperatorPassword: updateOperatorPassword,
        exportTenantOperator: exportTenantOperator
    };
})();

var addTenantOperator = (function () {
    function init() {
        validateRule();
    };

    function save() {
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/save",
            data: $('#frmOperator').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    tenantOperator.goBack();
                } else {
                    parent.layer.alert(data.message)
                }
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmOperator").validate({
            rules: {
                tenantOperatorCode: {
                    required: true,
                    minlength: 9,
                    maxlength: 9
                },
                operatorName: "required",
                loginName: {
                    required: true
                },
                password: {
                    required: true
                },
                contactName: "required",
                phone: {
                    required: true
                }
            },
            messages: {
                tenantOperatorCode: {
                    required: icon + "请输入运营商编号",
                    minlength: icon + "机构代码长度为9位",
                    maxlength: icon + "机构代码长度为9位"
                },
                operatorName: icon + "请输入运营商名称",
                loginName: {
                    required: icon + "请输入登录帐号"
                },
                password: {
                    required: icon + "请输入登录密码"
                },
                contactName: icon + "请输入联系人名称",
                phone: {
                    required: icon + "请输入电话号码"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();

var editTenantOperator = (function () {
    function init() {
        validateRule();
    };

    function update() {
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/update",
            data: $('#frmOperator').serialize(),
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    tenantOperator.goBack();
                } else {
                    parent.layer.alert(data.message)
                }
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmOperator").validate({
            rules: {
                tenantOperatorCode: {
                    // required: true,
                    // minlength: 9,
                    // maxlength: 9
                },
                operatorName: "required",
                contactName: "required",
                phone: {
                    // required: true
                }
            },
            messages: {
                tenantOperatorCode: {
                    // required: icon + "请输入运营商编号",
                    // minlength: icon + "机构代码长度为9位",
                    // maxlength: icon + "机构代码长度为9位"
                },
                operatorName: icon + "请输入运营商名称",
                contactName: icon + "请输入联系人名称",
                phone: {
                    // required: icon + "请输入电话号码"
                }
            },
            submitHandler: function (form) {
                update();
            }
        })
    }

    return {
        init: init
    };
})();
